package school.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import school.domain.Offer;
import school.domain.Product;
import school.domain.Record;
import school.mapper.OfferMapper;
import school.mapper.ProductMapper;
import school.mapper.RecordMapper;
import school.support.BaseController;

import java.util.Date;

@RequestMapping("offer")
@Controller
public class OfferController extends BaseController {

    @Autowired
    private OfferMapper offerMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private RecordMapper recordMapper;

    /**
     * 竞价
     * @return
     */
    @RequestMapping("send")
    public String send(Integer price ,Integer productid){
        session.removeAttribute("errorMsg");
        Product product = productMapper.selectByPrimaryKey(productid);
        updateProduct(product);

        //竞价判断
        Record record = new Record();
        record.setProductid(productid);
        record.setUserid(frontUser().getId());
        record = recordMapper.selectOne(record);
        if(null == record) {
            session.setAttribute("error","error");
            return refresh();
        }


        if(!product.getStatus().equals("拍卖中")){
            session.setAttribute("errorMsg","该商品不能拍卖，不在拍卖的时间范围");
            return refresh();
        }
        if(price < product.getCurrent()){
            session.setAttribute("errorMsg","您的出价必须高于现在的出价");
            return refresh();
        }
        product.setCount(product.getCount()+1);
        product.setCurrent(price);
        product.setIllegalprice(price);
        product.setIllegaluser(frontUser().getId());
        productMapper.updateByPrimaryKey(product);

        //添加记录
        Offer offer = new Offer();
        offer.setAddtime(new Date());
        offer.setPrice(price);
        offer.setProductid(productid);
        offer.setUserid(frontUser().getId());
        offerMapper.insertSelective(offer);
        session.setAttribute("errorMsg","竞价成功");
        return refresh();
    }

    @RequestMapping("pay/{id}")
    public String pay(@PathVariable Integer id){
        Record record = new Record();
        record.setProductid(id);
        record.setUserid(frontUser().getId());
        recordMapper.insert(record);
        session.setAttribute("errorMsg","支付成功，可以参与竞拍了");
        return refresh();
    }
}
